import { ElInput, ElOption, ElSelect } from 'element-plus'
import { isFunction } from '@vueuse/core'
import type { InputField, QueryFormField, SelectField } from '@/components/QueryForm/types'
import { isRef } from 'vue'

function isInputField<T>(field: QueryFormField<T>): field is InputField<T> {
  return field.type === 'Input'
}

function isSelectField<T>(field: QueryFormField<T>): field is SelectField<T> {
  return field.type === 'Select'
}
export default function ({ form, field, emit }: { field: QueryFormField<string>; form: Record<string, any>; emit: (value: any) => void }) {
  if (isInputField(field))
    return <ElInput {...field.props} modelValue={form[field.key]} onUpdate:modelValue={emit} />
  if (isSelectField(field)) {
    return (
      <ElSelect modelValue={form[field.key]} onUpdate:modelValue={emit} {...field.props} clearable>
        {
          isFunction(field.enums)
            ? field.enums()
            : isRef(field.enums) ?
              field.enums.value.map(option => (
                <ElOption value={option.value} {...option.props} key={option.value} label={option.label}>
                  {option.label}
                </ElOption>
              ))
              : field.enums.map(option => (
                <ElOption value={option.value} {...option.props} key={option.value} label={option.label}>
                  {option.label}
                </ElOption>
              ))
        }
      </ElSelect>
    )
  }
  return null
}
